package com.example.demo.controller;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.service.OrderItemService;
import com.example.demo.service.OrdersService;
import com.example.demo.service.UserService;
import com.example.demo.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.example.demo.util.TokenUtils.genToken;
import static com.example.demo.util.TokenUtils.getCurrentUser;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    UserService userService;
    @PostMapping
    public Result save(@RequestBody Orders orders) {
        if (orders.getId() == null) {
        }
        ordersService.saveOrUpdate(orders);
        return Result.suc();
    }

    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody List<Shoppingcart> carts) {
        ordersService.addOrder(carts);
        return Result.suc();
    }

    @PostMapping("/addOther")
    public Result addOther(@RequestBody Weifen weifen) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderno",weifen.getOrderno());
        List<Orders> list = ordersService.list(queryWrapper);
        Orders orders = list.get(0);
        orders.setDispatcher(weifen.getStaff());
        System.out.println(orders);
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name",weifen.getStaff());
        List<User> list1 = userService.list(queryWrapper1);
        User user = list1.get(0);
        orders.setPhone(user.getPhone());
        ordersService.updateOrder(orders);
        return Result.suc();
    }

    @PostMapping("/status")
    public Result addOrder(@RequestBody Orders orders) {
        ordersService.updateOrder(orders);
        return Result.suc();
    }

    @PostMapping("/status2")
    public Result addOrder2(@RequestBody Yifenpei yifenpei) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderno",yifenpei.getOrderno());
        List<Orders> list = ordersService.list(queryWrapper);
        Orders orders = list.get(0);
        orders.setStatus(yifenpei.getStatus());
        ordersService.saveOrUpdate(orders);
        return Result.suc();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        ordersService.removeById(id);
        return Result.suc();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        ordersService.removeByIds(ids);
        return Result.suc();
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.suc(ordersService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
//        User currentUser = TokenUtils.getCurrentUser();
//        if (currentUser.getRole().equals("ROLE_USER")) {
//            queryWrapper.eq("userid", currentUser.getId());
//        }
        Page<Orders> page = ordersService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for (Orders record : page.getRecords()) {
            Integer id = record.getId();
            List<OrderItem> orderItems = orderItemService.list(new QueryWrapper<OrderItem>().eq("order_id", id));
            record.setOrderItems(orderItems);
        }
        return Result.suc(page);
    }

    @GetMapping("/page2")
    public Result findPage2(
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        String userId = JWT.decode(token).getAudience().get(0);
      queryWrapper.eq("userid",Integer.valueOf(userId)) ;


//        User currentUser = TokenUtils.getCurrentUser();
//        if (currentUser.getRole().equals("ROLE_USER")) {
//            queryWrapper.eq("userid", currentUser.getId());
//        }
        Page<Orders> page = ordersService.page(new Page<>(pageNum, pageSize), queryWrapper);
        for (Orders record : page.getRecords()) {
            Integer id = record.getId();
            List<OrderItem> orderItems = orderItemService.list(new QueryWrapper<OrderItem>().eq("order_id", id));
            record.setOrderItems(orderItems);
        }
        return Result.suc(page);
    }
}
